package com.btnc.observer;

import java.io.StringReader;
import java.net.URISyntaxException;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.activemq.ActiveMQConnection;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class POSSubscriber441 implements MessageListener {
	private static final Logger logger = Logger
			.getLogger(POSSubscriber441.class);
	private String posId;
	private String connectionURL;

	public String getConnectionURL() {
		return connectionURL;
	}

	public void setConnectionURL(String connectionURL) {
		this.connectionURL = connectionURL;
	}

	public String getPosId() {
		return posId;
	}

	public void setPosId(String posId) {
		this.posId = posId;
	}

	@Override
	public void onMessage(Message btncMessage) {
		if (!(btncMessage instanceof TextMessage)) {
			logger.error("expected message of type TextMessage, ignoring this message");
			return;
		}
		try {
			String xmlMessage = ((TextMessage) btncMessage).getText();
			logger.info("received notification " + xmlMessage);
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xmlMessage));

			Document doc = db.parse(is);
			NodeList nodes = doc.getElementsByTagName("movingnote");
			Element element = (Element) nodes.item(0);
			String poslist = getTextValue(element, "poslist");
			String[] posArray = poslist.split(",");
			for (int i = 0; i < posArray.length; i++) {
				String pos = posArray[i];
				if (pos.equals(posId)) {
					logger.info("received moving note: " + getMovingNote(element.getAttribute("id")));
					break;
				}
			}
		} catch (Exception e) {
			logger.error("exception while processing message", e);
		}
	}
	
	private String getMovingNote(String id) {
		ActiveMQConnection connection;
		String noteXML = "";
		try {
			connection = ActiveMQConnection
					.makeConnection(connectionURL);
			connection.start();
			Session session = connection.createSession(false,
					Session.AUTO_ACKNOWLEDGE);
			Destination destination = session.createQueue("movingnote.request.input");
			TextMessage movingNote = session.createTextMessage();
			movingNote.setText("<movingnote format=\"node\"><id>"+id+"</id></movingnote>");
			MessageProducer producer = session.createProducer(destination);
			logger.info("Send request for new moving note : "+"<movingnote format=\"node\"><id>"+id+"</id></movingnote>");
			producer.send(movingNote);

			Destination responseDestination = session
					.createQueue("movingnote.response.output");
			MessageConsumer consumer = session
					.createConsumer(responseDestination);
			TextMessage movingnoteMessage = (TextMessage) consumer.receive();
			noteXML = movingnoteMessage.getText();
			connection.close();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return noteXML;
	}

	private String getTextValue(Element ele, String tagName) {
		String textVal = null;
		NodeList nl = ele.getElementsByTagName(tagName);
		if (nl != null && nl.getLength() > 0) {
			Element el = (Element) nl.item(0);
			textVal = el.getFirstChild().getNodeValue();
		}

		return textVal;
	}
}
